// #include "../source/server.hpp"

// int main() {
//     Socket lst;
//     lst.CreateServer(8086);
//     while (1) {
//         int newfd = lst.Accept();
//         if(newfd < 0) {
//             continue;
//         }
//         Socket cli(newfd);
//         char buffer[1024] = {0};
//         int ret = cli.Recv(buffer, sizeof(buffer) - 1);
//         if(ret < 0) {
//             cli.Close();
//             continue;
//         }
//         cli.Send(buffer, ret);
//         cli.Close();
//     }
//     lst.Close();
//     return 0;
// }
#include "../source/server.hpp"
#include <cstddef>
#include <sys/socket.h>

void HandleClose(Channel* channel) {
    // std::cout << "close: " << channel->Fd() << std::endl;
    DBG_LOG("close fd:%d", channel->Fd());
    channel->Remove(); // 移除监控
    delete channel;
}
void HandleRead(Channel* channel) {
    int fd = channel->Fd();
    char buf[1024] = {0};
    int n = recv(fd, buf, 1023, 0);
    if(n <= 0) {
        return HandleClose(channel);
    }
    // std::cout << buf << std::endl;
    DBG_LOG("%s", buf);
    channel->EnableWrite();
}
void HandleWrite(Channel* channel) {
    int fd = channel->Fd();
    const char* data = "你好啊";
    int n = send(fd, data, strlen(data), 0);
    if(n < 0) {
        return HandleClose(channel);
    }
    channel->DisableWrite();
}
void HandleError(Channel* channel) {
    return HandleClose(channel);
}
void HandleEvent(EventLoop* loop, Channel* channel, uint64_t timerid) {
    // std::cout << "有一个事件！" << std::endl;///
    // 添加事件刷新
    loop->TimerRefresh(timerid);
}
void Acceptor(EventLoop* loop, Channel* lst_channel){
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    if(newfd < 0) {
        return;
    }
    uint64_t timerid = rand() % 10000;
    Channel* channel = new Channel(loop, newfd);
    channel->SetReadCallback(std::bind(HandleRead, channel));
    channel->SetWriteCallback(std::bind(HandleWrite, channel));
    channel->SetCloseCallback(std::bind(HandleClose, channel));
    channel->SetErrorCallback(std::bind(HandleError, channel));
    channel->SetEventCallback(std::bind(HandleEvent, loop, channel, timerid));
    loop->TimerAdd(timerid, 10, std::bind(HandleClose, channel));
    channel->EnableRead();
}
int main() {
    srand(time(nullptr));
    EventLoop loop;
    Socket lst_sock;
    lst_sock.CreateServer(8085);
    Channel channel(&loop, lst_sock.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));
    channel.EnableRead();
    while (1) {
        loop.Start();
    }
    lst_sock.Close();
    return 0;
}